package cn.jarlen.jwt.tools;

import android.Manifest;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.jarlen.myapplication.R;

import cn.jarlen.jwt.tools.adapter.MenuAdapter;
import cn.jarlen.jwt.tools.menu.IMenuProcess;
import cn.jarlen.jwt.tools.menu.MenuBean;
import cn.jarlen.jwt.tools.menu.MenuManager;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, MenuAdapter.OnMenuItemClickListener {

    private RecyclerView rvMenu;
    private MenuAdapter menuAdapter;

    public static final int REQ_PERMISSIONS = 7;

    private final String[] PERMISSIONS = {
            Manifest.permission.INTERNET,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_PHONE_NUMBERS,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rvMenu = findViewById(R.id.rv_menu);
        rvMenu.setLayoutManager(new GridLayoutManager(this, 2));

        menuAdapter = new MenuAdapter(this);
        rvMenu.setAdapter(menuAdapter);
        menuAdapter.setOnMenuItemClickListener(this);
        menuAdapter.addDataList(MenuManager.buildMenu());

        if (!EasyPermissions.hasPermissions(this, PERMISSIONS)) {
            EasyPermissions.requestPermissions(new PermissionRequest.Builder(this, REQ_PERMISSIONS, PERMISSIONS).build());
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        finish();
    }


    @Override
    public void onMenuItemClick(MenuBean menuBean) {
        Class<? extends IMenuProcess> menuClass = menuBean.getMenuClass();
        if (menuClass == null) {
            return;
        }

        try {
            IMenuProcess menuProcess = menuClass.newInstance();
            menuProcess.onExecute(this);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
